from flask import Flask, request, render_template
import MySQLdb
app = Flask(__name__)
# 配置数据库连接
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = '3306'
app.config['MYSQL_DATABASE_DB'] = 'school'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'

# 初始化 MySQLdb 连接
def get_db_connection():
    return MySQLdb.connect(
        user=app.config['MYSQL_DATABASE_USER'],
        passwd=app.config['MYSQL_DATABASE_PASSWORD'],
        db=app.config['MYSQL_DATABASE_DB'],
        host=app.config['MYSQL_DATABASE_HOST']
    )

@app.route('/')
def index():
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute('SELECT * FROM questions')
    questions = cursor.fetchall()
    cursor.close()
    conn.close()
    return render_template('index.html', questions=questions)

@app.route('/submit', methods=['POST'])
def submit():
    answers = request.form
    score = 0
    total = 0
    conn = get_db_connection()
    cursor = conn.cursor()
    for question_id, user_answer in answers.items():
        cursor.execute('SELECT correct_answer FROM questions WHERE id = %s', (question_id,))
        correct_answer = cursor.fetchone()[0]
        total += 1
        if user_answer == correct_answer:
            score += 1
    cursor.close()
    conn.close()
    return f'你的分数: {score}/{total}'

if __name__ == '__main__':
    app.run(debug=True)